import { useEffect, useRef, useCallback } from 'react';
import { PerformanceMonitor } from '../utils/performance';

/**
 * 性能监控Hook
 */
export function usePerformance() {
  const monitor = useRef(PerformanceMonitor.getInstance());

  const startTiming = useCallback((name: string) => {
    monitor.current.startTiming(name);
  }, []);

  const endTiming = useCallback((name: string) => {
    return monitor.current.endTiming(name);
  }, []);

  const getMetrics = useCallback(() => {
    return monitor.current.getMetrics();
  }, []);

  return {
    startTiming,
    endTiming,
    getMetrics,
  };
}

/**
 * 组件渲染性能监控Hook
 */
export function useRenderPerformance(componentName: string) {
  const { startTiming, endTiming } = usePerformance();

  useEffect(() => {
    startTiming(`${componentName}-render`);

    return () => {
      endTiming(`${componentName}-render`);
    };
  }, [componentName, startTiming, endTiming]);
}

/**
 * 内存泄漏检测Hook
 */
export function useMemoryLeakDetection(componentName: string) {
  const leakDetector = useRef(createMemoryLeakDetector());

  useEffect(() => {
    leakDetector.current.register(componentName);

    return () => {
      leakDetector.current.unregister(componentName);
    };
  }, [componentName]);

  return {
    getActiveComponents: () => leakDetector.current.getActiveComponents(),
  };
}

/**
 * 防抖Hook
 */
export function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
}

/**
 * 节流Hook
 */
export function useThrottle<T>(value: T, limit: number): T {
  const [throttledValue, setThrottledValue] = useState<T>(value);
  const lastRan = useRef<number>(Date.now());

  useEffect(() => {
    const handler = setTimeout(() => {
      if (Date.now() - lastRan.current >= limit) {
        setThrottledValue(value);
        lastRan.current = Date.now();
      }
    }, limit - (Date.now() - lastRan.current));

    return () => {
      clearTimeout(handler);
    };
  }, [value, limit]);

  return throttledValue;
}

/**
 * 虚拟滚动Hook
 */
export function useVirtualScroll({
  itemHeight,
  containerHeight,
  totalItems,
  overscan = 5,
}: {
  itemHeight: number;
  containerHeight: number;
  totalItems: number;
  overscan?: number;
}) {
  const [scrollTop, setScrollTop] = useState(0);

  const { startIndex, endIndex } = useMemo(() => {
    return calculateVirtualRange(scrollTop, totalItems, {
      itemHeight,
      containerHeight,
      overscan,
    });
  }, [scrollTop, totalItems, itemHeight, containerHeight, overscan]);

  const totalHeight = totalItems * itemHeight;
  const offsetY = startIndex * itemHeight;

  const handleScroll = useCallback((e: React.UIEvent<HTMLDivElement>) => {
    setScrollTop(e.currentTarget.scrollTop);
  }, []);

  return {
    scrollTop,
    startIndex,
    endIndex,
    totalHeight,
    offsetY,
    handleScroll,
  };
}

/**
 * 图片懒加载Hook
 */
export function useLazyImage(src: string, options?: IntersectionObserverInit) {
  const [isLoaded, setIsLoaded] = useState(false);
  const [isInView, setIsInView] = useState(false);
  const imgRef = useRef<HTMLImageElement>(null);

  useEffect(() => {
    const img = imgRef.current;
    if (!img) return;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsInView(true);
          observer.disconnect();
        }
      },
      options
    );

    observer.observe(img);

    return () => observer.disconnect();
  }, [options]);

  useEffect(() => {
    if (!isInView) return;

    const img = new Image();
    img.onload = () => setIsLoaded(true);
    img.src = src;
  }, [isInView, src]);

  return {
    imgRef,
    isLoaded,
    isInView,
  };
}

// 导入必要的依赖
import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
import { createMemoryLeakDetector, calculateVirtualRange } from '../utils/performance';
